<template>
  <el-dialog width="80%" v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="140px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="名称"></el-input>
        <el-radio-group v-model="dataForm.title">
          <el-radio :label="item" v-for="(item, index) in titles" :key="index">{{ item }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="content" label="内容">
        <!-- <WangEditor v-model="dataForm.content"></WangEditor> -->
        <TinyMce v-model="dataForm.content" :init="{ height: 600 }"></TinyMce>
      </el-form-item>
      <el-form-item label="封面" prop="uploadUrl">
        <el-upload :action="uploadUrl" ref="uploadRef" :multiple="false" list-type="picture-card" :limit="1" :before-upload="uploadBeforeUploadHandle" :on-success="uploadSuccessHandle">
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model="dataForm.author" placeholder="作者"></el-input>
      </el-form-item>
      <el-form-item label="摘要" prop="digest">
        <el-input v-model="dataForm.digest" type="textarea" placeholder="图文消息的摘要,默认抓取正文前54个字"></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio :label="1">娱乐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="status">
        <ren-select v-model="dataForm.status" dict-type="wx_articles_status" placeholder="状态"></ren-select>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import { Plus, Delete } from "@element-plus/icons-vue";
import TinyMce from "@/components/tinymce/src/index.vue";
import WangEditor from "@/components/wang-editor/index.vue";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const uploadRef: any = ref(null);
const dataForm = reactive({
  id: "",
  title: "",
  content: "",
  author: "",
  digest: "",
  type: 1,
  status: 1
});

const rules = ref({
  title: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  content: [{ required: true, message: t("validate.required"), trigger: "blur" }]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

const uploadUrl = ref(`${app.api}/wechat/publicarticles/add_material?articleId=${dataForm.id}`);
const titles = ref([]);

const splitAndCleanData = (data: any) => {
  // 先按照 &split; 进行拆分
  let splitData = data.split("&split;");

  // 遍历拆分后的数组，去除每个元素中的 \ 和引号
  for (let i = 0; i < splitData.length; i++) {
    splitData[i] = splitData[i].replace(/\\/g, "").replace(/"/g, "");
  }

  return splitData;
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/wechat/publicarticles/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    if (res.data.titleExt) {
      titles.value = splitAndCleanData(res.data.titleExt);
    }
    uploadUrl.value = `${app.api}/wechat/publicarticles/add_material?articleId=${dataForm.id}&token=${getToken()}`;
  });
};

const uploadBeforeUploadHandle = (file: any) => {
  console.log(dataForm);
  if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
    ElMessage.error(t("upload.tip", { format: "jpg、png、gif" }));
    return false;
  }
};
const uploadSuccessHandle = (res: any) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }
  visible.value = false;
  uploadRef.value.clearFiles();
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/wechat/publicarticles", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
